package com.multi.publicly.utils;

import com.alibaba.fastjson2.JSONObject;
import com.multi.common.constant.CacheConstants;
import com.multi.common.constant.SourceConstant;
import com.multi.tenant.util.HttpServiceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;


/**
 * @Description 微信工具类
 * @ClassName WechatUtil
 * @Author pzj
 * @Data 2024/3/18 9:56
 */
@Slf4j
@Component
public class WechatUtil {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取access_token
     *
     * @param appid
     * @param secret
     * @return
     */
    public String getAccessToken(String appid, String secret) throws Exception {
        //设置获取accessTokenUrl
        String accessTokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appid, secret);
        JSONObject jsonObject = restTemplate.getForObject(accessTokenUrl, JSONObject.class);
        log.info("获取小程序access_token={}", jsonObject);
        String accessToken = (String) jsonObject.get(SourceConstant.ACCESS_TOKEN);
        return accessToken;
    }

    /**
     * 获取手机号
     *
     * @param accessToken
     * @param code
     * @return
     */
    public String getphoneByToken(String accessToken, String code) {
        // 接口调用凭证：accessToken
        String phoneUrl = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", accessToken);
        //设置请求体
        HashMap<String, String> requestParam = new HashMap<>();
        requestParam.put("code", code);
        JSONObject jsonObject = restTemplate.postForObject(phoneUrl, requestParam, JSONObject.class);
        log.info("获取小程序phone信息={}", jsonObject);
        LinkedHashMap<String, String> phone_info = (LinkedHashMap<String, String>) jsonObject.get("phone_info");
        return phone_info.get("phoneNumber");
    }

    /**
     * 获取微信OPENID信息
     *
     * @param appid
     * @param secret
     * @param code
     * @return
     */
    public String getOpenId(String appid, String secret, String code) {
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appid, secret, code);
        //设置请求头信息
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("text/plain");
        headers.setContentType(type);
        String forObjectInfo = restTemplate.postForObject(url, headers, String.class);
        log.info("获取openID信息返回：{}", forObjectInfo);
        JSONObject jsonObject = JSONObject.parseObject(forObjectInfo);
        return jsonObject.get("openid").toString();
    }

//    //敏感词检测
//    public static boolean msgCheck(String content, String openid) {
//        String token = null;
//        try {
//            token = getAccessToken(WechatConstants.APP_ID, WechatConstants.APP_SECRET);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Map<String, Object> paramMap = new HashMap<String, Object>(1);
//        paramMap.put("content", content);
//        paramMap.put("scene", 1);//场景枚举值（1 资料；2 评论；3 论坛；4 社交日志）
//        paramMap.put("version", 2);//接口版本号，2.0版本为固定值2
//        paramMap.put("openid", openid);
//        Object result = HttpUtil.post("https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + token, JSONUtil.toJsonPrettyStr(paramMap));
//        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(result);
//        boolean flag = false;
//        cn.hutool.json.JSONObject results = JSONUtil.parseObj(jsonObject.get("result").toString());
//        //内容含有违法违规内容
//        if (!"pass".equals(results.get("suggest").toString())) {
//            flag = true;
//        }
//        return flag;
//    }

//    //敏感图片检测
//    public static boolean imgCheck(String url, String openid) {
//        String token = null;
//        try {
//            token = getAccessToken(WechatConstants.APP_ID, WechatConstants.APP_SECRET);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Map<String, Object> paramMap = new HashMap<String, Object>(1);
//        paramMap.put("media_url", url);
//        paramMap.put("media_type", 2);//图片检测
//        paramMap.put("version", 2);//接口版本号，2.0版本为固定值2
//        paramMap.put("scene", 1);//场景枚举值（1 资料；2 评论；3 论坛；4 社交日志）
//        paramMap.put("openid", openid);
//        Object result = HttpUtil.post("https://api.weixin.qq.com/wxa/media_check_async?access_token=" + token, JSONUtil.toJsonPrettyStr(paramMap));
//        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(result);
//        boolean flag = false;
//        //内容不正常
//        cn.hutool.json.JSONObject results = JSONUtil.parseObj(jsonObject.toString());
//        if (!"ok".equals(results.get("errmsg").toString())) {
//            flag = true;
//        }
//        return flag;
//    }
}
